package cn.jfstu.freenote.dao.conf;

import cn.jfstu.freenote.dao.base.PageSortInterceptor;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * dao层配置
 * @author 贾俊峰
 * @version 1.0
 * @date 2016/11/29 14:08
 */
@Configuration
@MapperScan(basePackages = "cn.jfstu.freenote.dao", annotationClass = Repository.class)
@Import({DataSourceConfig.class})
@EnableTransactionManagement
public class DaoConfig {
    private static final Logger logger = LoggerFactory.getLogger(DaoConfig.class);

    @Resource
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        logger.info("注入sqlSessionFactory");
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/**/*Mapper.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("cn.jfstu.freenote.entity");
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PageSortInterceptor()});
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() throws SQLException {
        logger.info("注入transactionManager");
        return new DataSourceTransactionManager(dataSource);
    }
}
